package com.ptszyxx.popose.module.base.web;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.ptszyxx.popose.R;
import com.ptszyxx.popose.common.constants.BundleConstant;
import com.ptszyxx.popose.common.utils.YActivityUtil;
import com.ptszyxx.popose.databinding.ActivityWebViewPayBinding;
import com.ptszyxx.popose.module.base.web.vm.WebViewPayVM;
import com.ysg.base.BaseFragment;
import com.ysg.http.data.AppViewModelFactory;
import com.ysg.utils.YStringUtil;

import java.util.HashMap;
import java.util.Map;

public class WebViewPayActivity extends BaseFragment<ActivityWebViewPayBinding, WebViewPayVM> {
    private boolean isAnimStart = false;
    private int currentProgress;
    private String mUrl;
    private String payType;//1.支付宝， 2.微信

    @Override
    public int initVariableId() {
        return 0;
    }

    @Override
    public void initParam() {
        super.initParam();
        Bundle bundle = getArguments();
        if (bundle != null){
            mUrl = bundle.getString(BundleConstant.URL);
            payType = bundle.getString(BundleConstant.PAY_TYPE);
            viewModel.requestAction(payType);
        }
    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.activity_web_view_pay;
    }

    @Override
    public WebViewPayVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(WebViewPayVM.class);
    }

    @Override
    public void initView() {
        super.initView();
        binding.viewClose.setOnClickListener((view)-> YActivityUtil.getInstance().close(getActivity()));
        initWebView();
        initClient();
    }


    private void initWebView() {
        /* 设置支持Js */
        binding.mWebView.getSettings().setJavaScriptEnabled(true);
        /* 设置为true表示支持使用js打开新的窗口 */
        binding.mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

        /* 设置缓存模式 */
        binding.mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        binding.mWebView.getSettings().setDomStorageEnabled(true);

        /* 设置为使用webview推荐的窗口 */
        binding.mWebView.getSettings().setUseWideViewPort(true);
        /* 设置为使用屏幕自适配 */
        binding.mWebView.getSettings().setLoadWithOverviewMode(true);
        /* 设置是否允许webview使用缩放的功能,我演示设为false,不允许 */
        binding.mWebView.getSettings().setBuiltInZoomControls(false);
        /* 提高网页渲染的优先级 */
        binding.mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);

        /* HTML5的地理位置服务,设置为true,启用地理定位 */
        binding.mWebView.getSettings().setGeolocationEnabled(true);
        /* 设置可以访问文件 */
        binding.mWebView.getSettings().setAllowFileAccess(true);

        Map<String, String> extraHeaders = new HashMap<>();
        extraHeaders.put("Referer", "http://ptszyxx.com");
        binding.mWebView.loadUrl(mUrl, extraHeaders);
    }

    private void initClient() {
        if (!YStringUtil.contains(mUrl, "sandcash")){
            initWebViewClient();
        }

        // 获取网页加载进度
        binding.mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                currentProgress = binding.progressBar.getProgress();
                if (newProgress >= 100 && !isAnimStart) {
                    // 防止调用多次动画
                    isAnimStart = true;
                    binding.progressBar.setProgress(newProgress);
                    // 开启属性动画让进度条平滑消失
                    startDismissAnimation(binding.progressBar.getProgress());
                } else {
                    // 开启属性动画让进度条平滑递增
                    startProgressAnimation(newProgress);
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

        });
    }

    private void initWebViewClient() {
        binding.mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                binding.progressBar.setVisibility(View.VISIBLE);
                binding.progressBar.setAlpha(1.0f);
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("url", "----------------"+url);
                try {
                    if (url.startsWith("weixin")) {
                        isWxPay = true;
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    } else if (url.startsWith("alipay")) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    }else if (url.startsWith("https://wx.tenpay.com")) {
                        isWxPay = true;
                        Map<String, String> extraHeaders = new HashMap<>();
                        extraHeaders.put("Referer", "http://ptszyxx.com");
                        view.loadUrl(url, extraHeaders);
                    }else if ("zhiyu:back".equals(url)){//支付宝支付成功后，按“返回”建
                        YActivityUtil.getInstance().close(getActivity());
                    }else{
                        view.loadUrl(url);
                    }
                }catch (Exception e){
                }
                return true;
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        });

        binding.mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                try {
                    // 不处理下载，直接抛出去，
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(url));
                    startActivity(i);
                } catch (Exception ignored) {
                    // 无论如何不要崩溃，比如没有浏览器，
                }

            }
        });
    }

    /**
     * progressBar递增动画
     */
    private void startProgressAnimation(int newProgress) {
        ObjectAnimator animator = ObjectAnimator.ofInt(binding.progressBar, "progress", currentProgress, newProgress);
        animator.setDuration(300);
        animator.setInterpolator(new DecelerateInterpolator());
        animator.start();
    }

    /**
     * progressBar消失动画
     */
    private void startDismissAnimation(final int progress) {
        ObjectAnimator anim = ObjectAnimator.ofFloat(binding.progressBar, "alpha", 1.0f, 0.0f);
        anim.setDuration(1500);  // 动画时长
        anim.setInterpolator(new DecelerateInterpolator());
        // 关键, 添加动画进度监听器
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float fraction = valueAnimator.getAnimatedFraction();      // 0.0f ~ 1.0f
                int offset = 100 - progress;
                binding.progressBar.setProgress((int) (progress + offset * fraction));
            }
        });

        anim.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                // 动画结束
                binding.progressBar.setProgress(0);
                binding.progressBar.setVisibility(View.GONE);
                isAnimStart = false;
            }
        });
        anim.start();
    }

    boolean isWxPay = false;
    @Override
    public void onResume() {
        super.onResume();
        if(isWxPay){
            getActivity().finish();
            isWxPay = false;
        }
    }




}